package com.weirdor.wxchat.www.web;

import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sd4324530.fastweixin.api.*;
import com.github.sd4324530.fastweixin.api.config.ApiConfig;

import com.github.sd4324530.fastweixin.api.entity.Menu;
import com.github.sd4324530.fastweixin.api.enums.MediaType;
import com.github.sd4324530.fastweixin.api.enums.OauthScope;
import com.github.sd4324530.fastweixin.api.response.*;

import com.github.sd4324530.fastweixin.message.Article;
import com.github.sd4324530.fastweixin.message.BaseMsg;
import com.github.sd4324530.fastweixin.message.NewsMsg;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.github.sd4324530.fastweixin.message.req.*;
import com.github.sd4324530.fastweixin.servlet.WeixinControllerSupport;
import com.google.gson.Gson;
import com.weirdor.wxchat.module.entity.*;
import com.weirdor.wxchat.module.service.*;
import com.weirdor.wxchat.www.web.api.annotation.AuthIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * Created by weirdor on 2017/11/30.
 */
@Async
@RestController
@RequestMapping("/wx")
public class IndexController extends WeixinControllerSupport {

    private static final Logger log = LoggerFactory.getLogger(IndexController.class);

    private static final String TOKEN = "weirdor";

    @Autowired
    private ApiConfig apiConfig;

    @Autowired
    private IQywxGzentityService qywxGzentityService;

    @Autowired
    private IQywxTexttemplateService qywxTexttemplateService;

    @Autowired
    private IQywxNewstemplateService qywxNewstemplateService;

    @Autowired
    private IQywxNewsitemService qywxNewsitemService;

    @Autowired
    private IQywxMenuService qywxMenuService;
    @Autowired
    private IQywxAutoresponseService qywxAutoresponseService;
    @Autowired
    private  IQywxAutoresponseDefaultService qywxAutoresponseDefaultService;
    @Autowired
    private  IQywxGzuserinfoService qywxGzuserinfoService;

    /**
     * @param request
     * @param response
     * @throws Exception
     * @Title accessWechat
     * @Description 用于用户在微信端连接服务器
     */
    @AuthIgnore
    @RequestMapping(value = "/accessWechat", method = RequestMethod.GET)
    public void accessWechat(HttpServletRequest request, HttpServletResponse response) throws Exception {
        super.bindServer(request, response);
    }

    // 重写父类方法，处理对应的微信消息
    @Override
    protected BaseMsg handleTextMsg(TextReqMsg msg) {
        String content = msg.getContent(); // content 是用户输入的信息
        log.info("获取到的内容为{}", msg.getContent());
        EntityWrapper<QywxAutoresponse> wrapper = new EntityWrapper<>();
        wrapper.like("key_word", content.toUpperCase());
        QywxAutoresponse qywxAutoresponse = qywxAutoresponseService.selectOne(wrapper);
        if (qywxAutoresponse!=null){
            if (qywxAutoresponse.getMsgType().equals("text")) {
                EntityWrapper<QywxTexttemplate> ew=new EntityWrapper<>();
                ew.eq("id",qywxAutoresponse.getResContent());
                QywxTexttemplate qywxTexttemplat=qywxTexttemplateService.selectOne(ew);
                return new TextMsg(qywxTexttemplat.getTemplateContent());
            }
            if (qywxAutoresponse.getMsgType().equals("news")) {
                EntityWrapper<QywxNewstemplate> wrapper1=new EntityWrapper<>();
                wrapper1.eq("id", qywxAutoresponse.getResContent());
                QywxNewstemplate qywxNewstemplate = qywxNewstemplateService.selectOne(wrapper1);
                log.info("获取到template数据 {}", new Gson().toJson(qywxNewstemplate));
                EntityWrapper<QywxNewsitem> newsitemEntityWrapper=new EntityWrapper<>();
                newsitemEntityWrapper.eq("templateid",qywxAutoresponse.getResContent());
                List<QywxNewsitem> wxNewsitemList= qywxNewsitemService.selectList(newsitemEntityWrapper);
                log.info("获取到item数据 {}", new Gson().toJson(wxNewsitemList));
                List<Article> articleList=new ArrayList<>();
                wxNewsitemList.forEach(item->{
                    Article k=new Article();
                    k.setDescription(item.getDescription());
                    k.setTitle(item.getTitle());
                    k.setPicUrl(item.getImagePath());
                    k.setUrl(item.getUrl());
                    articleList.add(k);
                });
                return new NewsMsg(articleList);
            }
        }
       //未识别的回复语
        EntityWrapper<QywxAutoresponseDefault> entityWrapper=new EntityWrapper<>();
        entityWrapper.eq("iswork","1");
        QywxAutoresponseDefault qywxAutoresponseDefault=qywxAutoresponseDefaultService.selectOne(entityWrapper);
        if (qywxAutoresponseDefault.getMsgtype().equals("news")){
            EntityWrapper<QywxNewstemplate> wrapper1=new EntityWrapper<>();
            wrapper1.eq("id", qywxAutoresponseDefault.getTemplateid());
            QywxNewstemplate qywxNewstemplate = qywxNewstemplateService.selectOne(wrapper1);
            log.info("获取到template数据 {}", new Gson().toJson(qywxNewstemplate));
            EntityWrapper<QywxNewsitem> newsitemEntityWrapper=new EntityWrapper<>();
            newsitemEntityWrapper.eq("templateid",qywxAutoresponseDefault.getTemplateid());
            List<QywxNewsitem> wxNewsitemList= qywxNewsitemService.selectList(newsitemEntityWrapper);
            log.info("获取到item数据 {}", new Gson().toJson(wxNewsitemList));
            List<Article> articleList=new ArrayList<>();
            wxNewsitemList.forEach(item->{
                Article k=new Article();
                k.setDescription(item.getDescription());
                k.setTitle(item.getTitle());
                k.setPicUrl(item.getImagePath());
                k.setUrl(item.getUrl());
                articleList.add(k);
            });
            return new NewsMsg(articleList);
        }
        else {
            EntityWrapper<QywxTexttemplate> ew=new EntityWrapper<>();
            ew.eq("id",qywxAutoresponseDefault.getTemplateid());
            QywxTexttemplate qywxTexttemplat=qywxTexttemplateService.selectOne(ew);
            return new TextMsg(qywxTexttemplat.getTemplateContent());
        }
    }

    @Override
    protected BaseMsg handleLinkMsg(LinkReqMsg msg) {
        return super.handleLinkMsg(msg);
    }

    @Override
    protected BaseMsg handleVoiceMsg(VoiceReqMsg msg) {
        return super.handleVoiceMsg(msg);
    }

    @Override
    protected BaseMsg handleVideoMsg(VideoReqMsg msg) {
        return super.handleVideoMsg(msg);
    }

    /**
     * 关注触发
     */
    @Override
    protected BaseMsg handleSubscribe(BaseEvent event) {
        UserAPI userAPI = new UserAPI(apiConfig);
        GetUserInfoResponse getUserInfoResponse = userAPI.getUserInfo(event.getFromUserName());
        log.info("获取用户信息 {}", new Gson().toJson(getUserInfoResponse));
        //将用户信息存入数据中
        QywxGzuserinfo qywxGzuserinfo=new QywxGzuserinfo();
        qywxGzuserinfo.setName(getUserInfoResponse.getNickname());
        qywxGzuserinfo.setAvatar(getUserInfoResponse.getHeadimgurl());
        qywxGzuserinfo.setSubscribeTime(new Date(getUserInfoResponse.getSubscribeTime()));
        qywxGzuserinfo.setSubscribeStatus(getUserInfoResponse.getSubscribe().toString());
        qywxGzuserinfo.setProvince(getUserInfoResponse.getProvince());
        qywxGzuserinfo.setGender(getUserInfoResponse.getSex().toString());
        qywxGzuserinfo.setCreateDate(new Date());
        qywxGzuserinfo.setWeixinid(getUserInfoResponse.getOpenid());
        EntityWrapper<QywxGzuserinfo> entityWrapper=new EntityWrapper<>();
        entityWrapper.eq("weixinid",event.getFromUserName());
        QywxGzuserinfo info= qywxGzuserinfoService.selectOne(entityWrapper);
        if (info==null){
            qywxGzuserinfoService.insert(qywxGzuserinfo);
         }
        else {
            qywxGzuserinfo.setId(info.getId());
            qywxGzuserinfoService.updateById(qywxGzuserinfo);
        }

        EntityWrapper<QywxGzentity> wrapper = new EntityWrapper<>();
        wrapper.eq("is_work", "1");
        List<QywxGzentity> qywxGzentities=qywxGzentityService.selectList(wrapper);
        for (QywxGzentity qywxGzentity:qywxGzentities){
            switch (qywxGzentity.getTemplateType()){
                case "text":
                    EntityWrapper<QywxTexttemplate> we = new EntityWrapper<>();
                    we.eq("id", qywxGzentity.getTemplateId());
                    QywxTexttemplate qywxTexttemplate = qywxTexttemplateService.selectOne(we);
                    log.info("获取到text数据 {}", new Gson().toJson(qywxTexttemplate));
                    return  new TextMsg(qywxTexttemplate.getTemplateContent());
                case "news":
                    EntityWrapper<QywxNewstemplate> wrapper1=new EntityWrapper<>();
                    wrapper1.eq("id", qywxGzentity.getTemplateId());
                    QywxNewstemplate qywxNewstemplate = qywxNewstemplateService.selectOne(wrapper1);
                    log.info("获取到template数据 {}", new Gson().toJson(qywxNewstemplate));
                    EntityWrapper<QywxNewsitem> newsitemEntityWrapper=new EntityWrapper<>();
                    newsitemEntityWrapper.eq("templateid",qywxGzentity.getTemplateId());
                    List<QywxNewsitem> wxNewsitemList= qywxNewsitemService.selectList(newsitemEntityWrapper);
                    log.info("获取到item数据 {}", new Gson().toJson(wxNewsitemList));
                    List<Article> articleList=new ArrayList<>();
                    wxNewsitemList.forEach(item->{
                        Article k=new Article();
                        k.setDescription(item.getDescription());
                        k.setTitle(item.getTitle());
                        k.setPicUrl(item.getImagePath());
                        k.setUrl(item.getUrl());
                        articleList.add(k);
                    });
                    return new NewsMsg(articleList);

            }
        }
        return null;
    }



    @Override
    protected BaseMsg handleLocationMsg(LocationReqMsg msg) {

        return new TextMsg(msg.getLabel());
    }


    /**
     * 取消关注触发
     */
    @Override
    protected BaseMsg handleUnsubscribe(BaseEvent event) {
        log.info("有用户取消关注微信公众号");
        EntityWrapper<QywxGzuserinfo> entityWrapper=new EntityWrapper<>();
        entityWrapper.eq("weixinid",event.getFromUserName());
        QywxGzuserinfo qywxGzuserinfo=new QywxGzuserinfo();
        qywxGzuserinfo.setSubscribeStatus("0");
        qywxGzuserinfoService.update(qywxGzuserinfo,entityWrapper);
        return super.handleUnsubscribe(event);
    }

    @Override
    protected BaseMsg handleImageMsg(ImageReqMsg msg) {
        return new TextMsg("已经收到您的图片");
    }

    @AuthIgnore
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public GetUsersResponse User(HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserAPI userAPI = new UserAPI(apiConfig);
        return userAPI.getUsers("");
    }

    @AuthIgnore
    @RequestMapping(value = "/user/{nextOpenid}", method = RequestMethod.GET)
    public GetUsersResponse Userpage(HttpServletRequest request, HttpServletResponse response, @RequestParam String nextOpenid) throws Exception {
        UserAPI userAPI = new UserAPI(apiConfig);
        return userAPI.getUsers(nextOpenid);
    }


    @AuthIgnore
    @RequestMapping(value = "/accessWechat", method = RequestMethod.POST)
    public String Message(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return super.processRequest(request);
    }


    @AuthIgnore
    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public String Messages(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OauthAPI oauthAPI = new OauthAPI(apiConfig);
        return oauthAPI.getOauthPageUrl("http://weirdor.s1.natapp.cc", OauthScope.SNSAPI_USERINFO, "STATE");
    }


    @Override
    protected String getToken() {
        return TOKEN;
    }

    @AuthIgnore
    @GetMapping("/create-menu")
    public String createMenu() throws Exception {
        String json = "{\n" +
                " \"button\": [{\n" +
                " \"type\": \"CLICK\",\n" +
                " \"name\": \"今日歌曲s\",\n" +
                " \"key\": \"V1001_TODAY_MUSIC\"\n" +
                " }, {\n" +
                " \"name\": \"菜单\",\n" +
                " \"subButton\": [{\n" +
                " \"type\": \"VIEW\",\n" +
                " \"name\": \"搜索\",\n" +
                " \"url\": \"http://www.soso.com/\"\n" +
                " }, {\n" +
                " \"type\": \"VIEW\",\n" +
                " \"name\": \"视频\",\n" +
                " \"url\": \"http://v.qq.com/\"\n" +
                " }, {\n" +
                " \"type\": \"CLICK\",\n" +
                " \"name\": \"赞一下我们\",\n" +
                " \"key\": \"V1001_GOOD\"\n" +
                " }]\n" +
                " }]\n" +
                "}";
        EntityWrapper<QywxMenu> wrapper=new EntityWrapper<QywxMenu>();
        //查询所有的菜单
        List<QywxMenu> qywxMenus=qywxMenuService.selectList(wrapper);
        System.err.println(qywxMenus);
        //根据父类查询所有子类的菜单
        qywxMenus.forEach(k->{
           List<QywxMenu> qywxMenus1=  qywxMenuService.queryListParentId(k.getFatherId());
            System.out.println(qywxMenus1);
        });
        Map<String,Object> map=new HashMap<>();
        map.put("button","");
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(new Gson().toJson(qywxMenus));


        Menu menu = mapper.readValue(json, Menu.class);
        //创建菜单
      //  MenuAPI menuAPI = new MenuAPI(apiConfig);
      //  ResultType resultType = menuAPI.createMenu(menu);
        return null;
    }

}
